package com.example.controller;

import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@RestController
public class TestController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/test/db")
    public String testDB() {
        try {
            Connection connection = dataSource.getConnection();
            if (connection.isValid(2)) {
                return "数据库连接成功";
            } else {
                return "数据库连接失败";
            }
        } catch (SQLException e) {
            return "数据库连接异常: " + e.getMessage();
        }
    }

    @GetMapping("/test/redis")
    public String testRedis() {
        try {
            // 测试Redis连接
            redisUtil.set("test_key", "test_value");
            Object value = redisUtil.get("test_key");
            redisUtil.delete("test_key");
            return "Redis连接成功，测试值: " + value;
        } catch (Exception e) {
            return "Redis连接异常: " + e.getMessage();
        }
    }
}